package com.gridpower.spreadsheet.client.widgets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
/**
 * ElementPool will be frequently used by UI render when spreadsheet page
 * changed or too many cell to be rendered at a time.
 * 
 * @author 438
 *
 */
public class ElementPool {
	int blkSize = 10;
	protected HashMap elementPool = new HashMap();
	public ElementPool() {
		
	}
	public Element getElement(String tagName) {
		Element ret = null;
		ArrayList newList = null;
		if (elementPool.get(tagName) == null) {
			newList = new ArrayList();
			for (int i = 0; i < blkSize; ++i)
				newList.add(DOM.createElement(tagName));
			elementPool.put(tagName, newList);
		}
		if (newList == null) {
			newList = (ArrayList)elementPool.get(tagName);
			if (newList.size() == 0) {
				for (int i = 0; i < blkSize; ++i)
					newList.add(DOM.createElement(tagName));
			}
		}
		Iterator head = newList.iterator();// remove begin
		if (head.hasNext()) {
			ret = (Element)head.next();
			newList.remove(ret);
		}
		return ret;
	}
	// assure the element is useless when return it, return it and return it only once
	// another dangours is that if one clear the parent element of th element, will the 
	// element disapear?
	public void returnElement(Element elem) {
		String cls = elem.getTagName();
		ArrayList pool = (ArrayList)elementPool.get(cls);
		if (pool != null) {
			pool.add(elem);
		}
	}
}
